package cn.com.chengmandian.core.web.utils;

import cn.com.chengmandian.core.common.enums.ClientsEnum;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;

import java.util.HashMap;
import java.util.Map;

public class AgentTokenUtil {
    private AgentUser agentUser;

    private AgentInfo agentInfo;

    private ClientsEnum clientsEnum;

    private Map<String, Object> attrs;

    public AgentTokenUtil(AgentUser agentUser, AgentInfo agentInfo, ClientsEnum clientsEnum) {
        this.agentUser = agentUser;
        this.clientsEnum = clientsEnum;
        this.agentInfo = agentInfo;
    }

    public static AgentTokenUtil create(AgentUser loginUser, AgentInfo agentInfo, ClientsEnum clientsEnum) {
        return new AgentTokenUtil(loginUser, agentInfo, clientsEnum);
    }

    public AgentTokenUtil setAttr(String key, Object value) {
        if (this.attrs == null) this.attrs = new HashMap<>();
        this.attrs.put(key, value);
        return this;
    }

    public String build() {
        agentUser.setAttrs(attrs);
        agentUser.setExpireDate(DateUtil.offsetDay(DateUtil.date(), clientsEnum.getExpireDay()).getTime());

        // 设置头部信息
        Map<String, Object> headers = new HashMap<>(2);
        headers.put("Type", "Jwt");
        headers.put("alg", "HS256");
        return JWTUtil.createToken(headers, BeanUtil.beanToMap(agentUser), agentInfo.getTokenSecret().getBytes());
    }
}
